//
//  UITextField+QSExtension.m
//  test
//
//  Created by apple on 2016/11/12.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "UITextField+QSExtension.h"
#import <objc/runtime.h>

@interface UITextField()<UITextFieldDelegate>

@end

/** 占位文字颜色的属性 */
static NSString * const QSPlaceholderColorKey = @"placeholderLabel.textColor";

#pragma mark - 新增属性key
static NSString *shouldBeginEditBlockKey = @"shouldBeginEditBlockKey";
static NSString *didChangeBlockKey = @"didChangeBlockKey";
static NSString *endEditBlockKey = @"endEditBlockKey";
static NSString *returnKeyBlockKey = @"returnKeyBlockKey";
static NSString *limitTextLengthKey = @"limitTextLengthKey";
static NSString *textLengthOverLimitedBlockKey = @"textLengthOverLimitedBlockKey";
static NSString *limitDecimalDigitLengthKey = @"limitDecimalDigitLengthKey";

@implementation UITextField (QSExtension)
/**
 *  设置占位符颜色
 */
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    BOOL change = NO;
    
    // 保证有占位文字
    if (self.placeholder == nil) {
        self.placeholder = @" ";
        change = YES;
    }
    
    // 设置占位文字颜色
    [self setValue:placeholderColor forKeyPath:QSPlaceholderColorKey];
    
    // 恢复原状
    if (change) {
        self.placeholder = nil;
    }
}

/**
 *  获取占位符颜色
 */
- (UIColor *)placeholderColor
{
    return [self valueForKeyPath:QSPlaceholderColorKey];
}

#pragma mark - 是否允许开始编辑回调
- (void)setShouldBeginEditBlock:(BOOL (^)(void))shouldBeginEditBlock
{
    self.delegate = self.delegate ? self.delegate : self;
    objc_setAssociatedObject(self, &shouldBeginEditBlockKey, shouldBeginEditBlock, OBJC_ASSOCIATION_COPY);
}

- (BOOL (^)(void))shouldBeginEditBlock
{
    return objc_getAssociatedObject(self, &shouldBeginEditBlockKey);
}

#pragma mark - 内容改变回调
- (void)setDidChangeBlock:(void (^)(NSString *))didChangeBlock
{
    self.delegate = self.delegate ? self.delegate : self;
    objc_setAssociatedObject(self, &didChangeBlockKey, didChangeBlock, OBJC_ASSOCIATION_COPY);
}

- (void (^)(NSString *))didChangeBlock
{
    return objc_getAssociatedObject(self, &didChangeBlockKey);
}

#pragma mark - 结束编辑回调
- (void)setEndEditBlock:(void (^)(NSString *))endEditBlock
{
    self.delegate = self.delegate ? self.delegate : self;
    objc_setAssociatedObject(self, &endEditBlockKey, endEditBlock, OBJC_ASSOCIATION_COPY);
}

- (void (^)(NSString *))endEditBlock
{
    return objc_getAssociatedObject(self, &endEditBlockKey);
}

#pragma mark - return键事件回调
- (void)setReturnKeyBlock:(void (^)(NSString *))returnKeyBlock
{
    self.delegate = self.delegate ? self.delegate : self;
    objc_setAssociatedObject(self, &returnKeyBlockKey, returnKeyBlock, OBJC_ASSOCIATION_COPY);
}

- (void (^)(NSString *))returnKeyBlock
{
    return objc_getAssociatedObject(self, &returnKeyBlockKey);
}

#pragma mark - 限制输入的长度
- (void)setLimitTextLength:(NSInteger)limitTextLength
{
    [self addTarget:self action:@selector(limitTheTextLength:) forControlEvents:UIControlEventEditingChanged];
    objc_setAssociatedObject(self, &limitTextLengthKey, @(limitTextLength), OBJC_ASSOCIATION_COPY);
}

- (NSInteger)limitTextLength
{
    NSNumber *number = objc_getAssociatedObject(self, &limitTextLengthKey);
    return [number integerValue];
}

#pragma mark - 限制输入的长度
- (void)setLimitDecimalDigitLength:(NSInteger)limitDecimalDigitLength
{
    self.delegate = self.delegate ? self.delegate : self;
    objc_setAssociatedObject(self, &limitDecimalDigitLengthKey, @(limitDecimalDigitLength), OBJC_ASSOCIATION_COPY);
}

- (NSInteger)limitDecimalDigitLength
{
    NSNumber *number = objc_getAssociatedObject(self, &limitDecimalDigitLengthKey);
    return [number integerValue];
}

#pragma mark - 字符超过限制回调
- (void)setTextLengthOverLimitedBlock:(void (^)(NSInteger))textLengthOverLimitedBlock
{
    objc_setAssociatedObject(self, &textLengthOverLimitedBlockKey, textLengthOverLimitedBlock, OBJC_ASSOCIATION_COPY);
}

- (void (^)(NSInteger))textLengthOverLimitedBlock
{
    return objc_getAssociatedObject(self, &textLengthOverLimitedBlockKey);
}

/**
 *  限制字符长度
 */
- (void)limitTheTextLength:(UITextField *)textField
{
    if (textField == self) {
        
        if (textField.text.length > self.limitTextLength) {
            textField.text = [textField.text substringToIndex:self.limitTextLength];
            if (self.textLengthOverLimitedBlock) {
                self.textLengthOverLimitedBlock(self.limitTextLength);
            }
        }
    }
}

#pragma mark - UITextFieldDelegate
/**
 *  是否允许开始编辑
 *
 *  return yes：允许； no：不允许
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (self.shouldBeginEditBlock) {
        return self.shouldBeginEditBlock();
    }
    return YES;
}

/**
 *  进入编辑状态
 */
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    // 直接代码调用setText输入的会调用这个方法
    [textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    
    // 监控数据改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

/**
 *  直接代码调用setText输入的会调用这个方法
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    NSString * string = [change valueForKey:@"new"];
    if (self.didChangeBlock) {
        self.didChangeBlock(string);
    }
}

/**
 *  在某个区域改变字符
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.limitDecimalDigitLength > 0) {
        NSMutableString * futureString = [NSMutableString stringWithString:textField.text];
        [futureString  insertString:string atIndex:range.location];
        
        NSInteger flag = 0;
        const NSInteger limited = self.limitDecimalDigitLength;
        for (int i = (int)futureString.length - 1; i >= 0; i--) {
            
            if ([futureString characterAtIndex:i] == '.') {
                if (flag > limited) {
                    return NO;
                }
                break;
            }
            flag++;
        }
    }
    
    return YES;
}

/**
 *  输入内容改变
 */
-(void)textFiledDidChange:(NSNotification *)not
{
    // 获取输入框中的内容
    NSString * string = [not.object description];
    NSRange range = [string rangeOfString:@"\'"];
    NSString * subStr = [string substringFromIndex:range.location + 1];
    NSRange subRange = [subStr rangeOfString:@"\'"];
    NSString * text = [subStr substringToIndex:subRange.location];
    
    if (self.didChangeBlock) {
        self.didChangeBlock(text);
    }
}

/**
 *  结束编辑
 */
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    // 删除通知监听者
    [textField removeObserver:self forKeyPath:@"text"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (self.endEditBlock) {
        self.endEditBlock(textField.text);
    }
}

/**
 *  是否响应键盘的return按钮点击
 *
 *  return yes：响应； no：忽略
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.superview endEditing:YES];
    if (self.returnKeyBlock) {
        self.returnKeyBlock(textField.text);
    }
    return NO;
}
@end
